package com.zhoug.common.clip;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhoug.common.R;
import com.zhoug.common.utils.AppUtils;
import com.zhoug.common.utils.BitmapUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StatusBarUtils;

import java.io.File;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 裁剪图片
 *
 * @Author: 35574
 * @Date: 2022/7/22
 * @Description:
 */
public class ClipImageActivity extends AppCompatActivity {
    private static final String TAG = ">>>CutImageActivity";
    /**
     * 需要裁剪的图片路径
     */
    public static final String EXTRA_INPUT_DATA = "inputData";
    /**
     * 裁剪后输出图片存储地址
     */
    public static final String EXTRA_OUTPUT_DATA = "outputData";
    /**
     * 裁剪后输出图片存储格式,未设置outputData时自动生成路径时使用
     * {@link Bitmap.CompressFormat#JPEG#toString()}
     * {@link Bitmap.CompressFormat#PNG#toString()}
     * {@link Bitmap.CompressFormat#WEBP#toString()}
     */
    public static final String EXTRA_OUTPUT_FORMAT = "outputFormat";
    /**
     * 选择框是否可以拖动
     */
    public static final String EXTRA_FRAME_TRANS_ENABLE = "frameTransEnable";
    /**
     * 选择框是否可以缩放
     */
    public static final String EXTRA_FRAME_SCALE_ENABLE = "frameScaleEnable";
    /**
     * 选择框默认宽高比
     */
    public static final String EXTRA_FRAME_RATIO = "frameRatio";

    private String inputData;
    private String outputData;
    private Bitmap.CompressFormat outputFormat;
    private boolean frameTransEnable = true;
    private boolean frameScaleEnable = true;
    private float frameRatio = 0.75f;



    private TextView mBtnConfirm;
    private ImageView mBtnBack;
    private ClipImageView mClipImageView;
    private ClipFrameView mClipFrameView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_activity_cut_image);
        StatusBarUtils.setStatusBarColor(this, Color.BLACK);
        StatusBarUtils.setStatusBarTextColor(this, false, false);
        findViews();
        initParams();
        init();
        bindListener();
    }

    private void initParams() {
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            inputData = extras.getString(EXTRA_INPUT_DATA);
            outputData = extras.getString(EXTRA_OUTPUT_DATA);
            String outputFormatName = extras.getString(EXTRA_OUTPUT_FORMAT);
            if (null != outputFormatName) {
                try {
                    outputFormat = Bitmap.CompressFormat.valueOf(outputFormatName.toUpperCase());
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
            frameTransEnable=extras.getBoolean(EXTRA_FRAME_TRANS_ENABLE,true);
            frameScaleEnable=extras.getBoolean(EXTRA_FRAME_SCALE_ENABLE,true);
            frameRatio=extras.getFloat(EXTRA_FRAME_RATIO,0.75f);
        }
    }

    private void findViews() {
        mBtnConfirm = findViewById(R.id.btn_confirm);
        mBtnBack = findViewById(R.id.btn_back);
        mClipImageView = findViewById(R.id.clipImageView);
        mClipFrameView = findViewById(R.id.clipFrameView);
    }


    private void init() {
        mClipFrameView.setScaleEnabled(frameScaleEnable);
        mClipFrameView.setTranslateEnabled(frameTransEnable);
        mClipImageView.setFrameRatio(frameRatio);
        mClipImageView.setClipFrameView(mClipFrameView);
        if (null == inputData || !new File(inputData).exists()) {
            LogUtils.e(TAG, "inputData 为null或者文件不存在");
            finish();
            return;
        }
        try {
            Bitmap bitmap = BitmapUtils.decodeFile(inputData, 1, Bitmap.Config.ARGB_8888);
            mClipImageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
            Point screenSize = AppUtils.getScreenSize();
            Bitmap bitmap = BitmapUtils.decodeFile(inputData, screenSize.x, screenSize.y, Bitmap.Config.ARGB_8888);
            mClipImageView.setImageBitmap(bitmap);
        }
    }

    /**
     * 绑定监听器
     */
    private void bindListener() {
        mBtnBack.setOnClickListener(v -> finish());

        mBtnConfirm.setOnClickListener(v -> {
            Bitmap clipImage = null;
            try {
                clipImage = mClipImageView.getClipImage();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (clipImage == null) {
                toast("裁剪失败");
                return;
            }
            if (outputData == null) {
                outputData = getCacheImagePath();
            }
            boolean b = BitmapUtils.keepBitmap(clipImage, 100, outputData);
            if (b) {
                LogUtils.d(TAG, "裁剪成功:");
                Intent intent = new Intent();
                intent.putExtra(EXTRA_OUTPUT_DATA, outputData);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                toast("裁剪失败");
                LogUtils.e(TAG, "裁剪失败");
            }

        });
    }


    /**
     * 保存图片的缓存路径
     *
     * @return
     */
    public String getCacheImagePath() {
        File cacheDir = getExternalCacheDir();
        String suffix = ".jpg";
        if (outputFormat != null) {
            switch (outputFormat) {
                case PNG:
                    suffix = ".png";
                    break;
                case JPEG:
                    suffix = ".jpg";
                    break;
                case WEBP:
                    suffix = ".webp";
                    break;
            }
        }
        File file = new File(cacheDir, "image/" + System.currentTimeMillis() + suffix);
        if (!file.getParentFile().exists()) {
            boolean mkdirs = file.getParentFile().mkdirs();
        }
        return file.getAbsolutePath();
    }

    private void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}
